#!/bin/bash
set -e

shopt -s expand_aliases

if [ "$1" == "docker" ]; then
    alias sudo="";
    echo "Running within container";
fi

# Clone the repos
mkdir -p ~/arkcompiler
cd ~/arkcompiler
sudo apt update -y
sudo apt upgrade -y
sudo apt install wget -y
sudo apt install git -y
sudo rm -rf ~/arkcompiler/ets_frontend
sudo rm -rf ~/arkcompiler/runtime_core
yes | git clone -b OpenHarmony_feature_20250702 --single-branch git@gitcode.com:openharmony/arkcompiler_runtime_core.git runtime_core
yes | git clone -b OpenHarmony_feature_20250702 --single-branch git@gitcode.com:openharmony/arkcompiler_ets_frontend.git ets_frontend
cd ~/arkcompiler/runtime_core/static_core/tools

# Buil tools
sudo apt install gdb -y
sudo apt install curl -y
sudo apt install build-essential -y

# NVM Setup
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm install v18.20.8
nvm alias default v18.20.8

# Link the frontend to the core compiler
ln -s ~/arkcompiler/ets_frontend/ets2panda es2panda

cd ~/arkcompiler/runtime_core/static_core/
sudo ./scripts/install-deps-ubuntu -i=dev -i=test
sudo rm -rf third_party
bash ./scripts/install-third-party --force-clone

cd ~/arkcompiler
sudo rm -rf build

cmake -B build -GNinja ./runtime_core/static_core \
-DPANDA_WITH_TESTS=true \
-DCMAKE_C_COMPILER=clang-14 \
-DCMAKE_CXX_COMPILER=clang++-14 \
-DCMAKE_BUILD_TYPE=Debug \
-DPANDA_WITH_BENCHMARKS=false \
-DPANDA_WITH_BYTECODE_OPTIMIZER=true \
-DPANDA_CROSS_COMPILER=false;

cmake --build build
